<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.project.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报销金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入报销金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择审批状态"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.fm_ra_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fm:ra:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fm:ra:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="项目编号" align="center" prop="project.projectNo" />
      <el-table-column label="项目名称" align="center" prop="project.projectName" />
      <el-table-column label="申请编号" align="center" prop="applicationNo" />
      <el-table-column label="请款内容" align="center" prop="reason" />
      <el-table-column label="请款金额" align="center" prop="amount" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fm_ra_status" :value="scope.row.status" :dictName="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fm:ra:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fm:ra:del']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

<!--    新增/修改/查看弹窗    -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="申请编号" prop="applicationNo">
              <el-input v-model="form.applicationNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 1. 修正项目选择器的v-model绑定 -->
            <el-form-item label="项目名称" prop="projectId">
              <el-select
                v-model="form.projectId"
                placeholder="请选择项目"
                @change="handleProjectChange"
              >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model="form.projectNo" placeholder="根据项目自动匹配" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!-- 申请时间 -->
            <el-form-item label="申请时间" prop="applicationTime">
              <el-date-picker
                clearable
                v-model="form.applicationTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择申请时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 报销金额 -->
            <el-form-item label="报销金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入报销金额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 请款内容 -->
            <el-form-item label="请款内容" prop="reason">
              <el-input v-model="form.reason" type="textarea" placeholder="请输入请款内容" />
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
          <el-col :span="8">
            <!-- 申请人（当前登录用户） -->
            <el-form-item label="申请人" prop="userName">
              <el-input v-model="form.userName" placeholder="当前登录用户" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 收款方式 -->
            <el-form-item label="收款方式" prop="paymentMethod">
              <el-select
                v-model="form.paymentMethod"
                placeholder="请选择收款方式">
                <el-option
                  v-for="dict in dict.type.fm_ra_pm"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 收款人姓名 -->
            <el-form-item label="收款人姓名" prop="payName">
              <el-input v-model="form.payName" placeholder="请输入收款人姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!-- 收款银行 -->
            <el-form-item label="收款银行" prop="receiveBank">
              <el-select
                v-model="form.receiveBank"
                placeholder="请选择收款银行">
                <el-option
                  v-for="dict in dict.type.sys_re_bank"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 收款账号 -->
            <el-form-item label="收款账号" prop="receiveAccount">
              <el-input v-model="form.receiveAccount" placeholder="请输入收款账号" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-form-item label="审批备注" prop="approvalRemark" v-if="isApprovalView">
          <el-input v-model="form.approvalRemark" type="textarea" plceholder="请输入审批备注信息" disabled/>
        </el-form-item>
<!--         修改上传附件区域的处理逻辑，确保只保留单个文件 -->
        <el-form-item label="上传附件">
          <el-upload
            action="#"
          :on-change="handleFileChange"
          :file-list="fileList"
          :auto-upload="false"
          :on-remove="handleFileRemove"
          :limit="2"
          :on-exceed="handleExceed"
          accept=".excel,.xls,.doc,.docx,.pdf,.jpg,.png"
          drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">点击或拖拽文件到此处上传</div>
            <div class="el-upload__tip" slot="tip">支持格式：.excel .xls .doc .docx .pdf .jpg .png，仅支持单个文件上传,单个文件不能超过20MB</div>
          </el-upload>
        </el-form-item>
        <!-- 在上传组件下方添加预览区域 -->
        <el-form-item label="文件预览" v-if="fileList.length > 0">
          <div class="file-preview-container">
            <!-- 仅在添加模式且为图片时显示预览 -->
            <template v-if="isAddMode && isImageFile(fileList[0])">
              <el-image
                :src="getPreviewUrl(fileList[0])"
                :preview-src-list="[getPreviewUrl(fileList[0])]"
                fit="contain"
                class="image-preview"
              >
                <div slot="error" class="image-error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>

            <!-- 非添加模式（更新/查看）或非图片文件，统一显示下载区域 -->
            <template v-else>
              <div class="file-link">
                <i class="el-icon-document"></i>
                <span class="file-name">{{ fileList[0].name }}</span>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-download"
                  @click.stop="downloadFile(fileList[0])"
                >
                  下载
                </el-button>
              </div>
            </template>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="12" align="">
            <el-button v-if="isSub" type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="cancel">取 消</el-button>
        </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addApplication, delApplication, getApplication, listApplication, updateApplication} from "@/api/system/fm/ra"
import {parseTime} from "../../../utils/ruoyi";
import {getAllProject} from "@/api/pm/projects";
import dict from "@/utils/dict";

export default {
  name: "Application",
  dicts:['fm_ra_pm', 'fm_ra_status','sys_re_bank'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 显示预览区域
      isAddMode:false,
      isSub:false,
      // 总条数
      total: 0,
      // 报销申请表格数据
      applicationList: [],
      // 弹出层标题
      title: "",
      fileList: [], // 上传的文件列表
      // 是否显示审批内容
      isApprovalView: false,
      // 是否显示弹出层
      open: false,
      // 项目列表（后端返回的所有项目数据）
      projectList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicationNo: null,
        userId: null,
        amount: null,
        reason: null,
        applicationTime: null,
        status: null,
        approvalUserId: null,
        approvalTime: null,
        approvalRemark: null,
        remark: null,
        paymentMethod: null,     // 收款方式(1为现金,2为转账)
        payName: null,           // 收款人姓名
        receiveBank: null,       // 收款银行
        receiveAccount: null,    // 收款账号
        project:{
          projectNO: null,
          projectName: null,
        }
      },
      // 表单参数
      form: {
        applicationNo: "",       // 申请编号
        userId: null,            // 申请人ID（当前登录用户ID）
        userName: "",            // 申请人姓名（显示用）
        amount: null,            // 报销金额
        reason: "",              // 请款内容
        applicationTime: "",     // 申请时间
        status: "3",       // 状态，默认为待审批
        approvalUserId: null,    // 审批人ID
        approvalTime: "",        // 审批时间
        projectId: null,         // 修正：项目ID字段名统一为projectId
        projectNo: "",           // 项目编号（显示用）
        approvalRemark: "",      // 审批备注
        remark: null,            // 备注
        paymentMethod: undefined,     // 收款方式(1为现金,2为转账)
        receiveBank: "",         // 收款银行
        payName: "",             // 收款人姓名
        receiveAccount: "",       // 收款账号
        file: null,
        fileUrl: null,
      },
      // 表单校验
      rules: {
        // 修正：移除冗余的userId和status校验，保持必要校验
        projectId: [{ required: true, message: "请选择项目", trigger: "change" }],
        applicationTime: [{ required: true, message: "请选择申请时间", trigger: "change" }],
        amount: [
          { required: true, message: "请输入报销金额", trigger: "blur" },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入有效金额（最多两位小数）", trigger: "blur" }
        ],
        reason: [{ required: true, message: "请输入请款内容", trigger: "blur" }],
        paymentMethod: [{ required: true, message: "请选择收款方式", trigger: "change" }],
        payName: [{ required: true, message: "请输入收款人姓名", trigger: "blur" }],
        // 修正：根据收款方式动态校验银行和账号
        receiveBank: [
          { required: () => this.form.paymentMethod === '2', message: "请输入收款银行", trigger: "blur" }
        ],
        receiveAccount: [
          { required: () => this.form.paymentMethod === '2', message: "请输入收款账号", trigger: "blur" }
        ],
        // 完善审批人验证规则
        approvalUserId: [{ required: true, message: "请选择审批人", trigger: "change" }],
      }
    }
  },
  created() {
    this.getList()
    // 初始化时获取项目列表
    this.loadProjectOptions();
  },
  methods: {
    dict,
    parseTime,

    /** 查询报销申请列表 */
    getList() {
      this.loading = true
      listApplication(this.queryParams).then(response => {
        this.applicationList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false;
      })
    },
    // 判断是否为图片文件
    isImageFile(file) {
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      const ext = file.name.split('.').pop().toLowerCase();
      return imageTypes.includes(ext);
    },

    // 获取预览URL
    getPreviewUrl(file) {
      // 已上传的文件使用后端返回的URL，新选择的文件使用本地临时URL
      if (file.url) {
        return file.url;
      } else if (file.raw) {
        return URL.createObjectURL(file.raw);
      }
      return '';
    },

    // 修改下载文件方法，确保已上传文件使用服务器URL下载
    downloadFile(file) {
      if (file.url) {
        // 已上传的文件通过服务器URL下载（使用a标签强制下载）
        const a = document.createElement('a');
        // 处理跨域或特殊格式文件，添加download属性强制下载
        a.download = file.name;
        // 处理URL可能的相对路径问题
        a.href = file.url.startsWith('http') ? file.url : process.env.VUE_APP_BASE_API + file.url;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } else if (file.raw) {
        // 本地文件通过临时链接下载
        const url = URL.createObjectURL(file.raw);
        const a = document.createElement('a');
        a.href = url;
        a.download = file.name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }
    },
    loadProjectOptions() {
      getAllProject().then(response => {
        // 正确写法：从response中提取data字段的数组
        this.projectList = response.data || [];  // 关键修复：添加 .data
      }).catch(err => {
        console.error('加载项目列表失败', err);
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        ...this.form,  // 保留用户信息
        id: null,
        applicationNo: "",
        amount: null,
        reason: "",
        applicationTime: "",
        status: 3,
        approvalUserId: null,
        approvalTime: "",
        projectId: null,
        projectNo: "",
        approvalRemark: "",
        paymentMethod: undefined,
        receiveBank: "",
        payName: "",
        receiveAccount: "",
        file: null,
        fileUrl: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.loadProjectOptions()
      this.reset()
      this.open = true
      this.title = "添加报销申请"
      this.isApprovalView = false
      // 新增：设置为添加模式
      this.isAddMode = true
      this.isSub=true;
      // 新增：默认申请时间为今天
      this.form.applicationTime = parseTime(new Date(), '{y}-{m}-{d}')
    },
    // 修改 handleView 方法中的项目信息回显逻辑
    handleView(row) {
      if (row){
        this.reset()
        getApplication(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.isSub=false;
          // 新增：设置为非添加模式
          this.isAddMode = false
          this.form.paymentMethod = this.form.paymentMethod?.toString();
          this.form.userName = response.data.user?.userName || '';
          this.title = "查看报销申请";
          this.isApprovalView = true;

          // 处理文件列表回显
          if (this.form.fileUrl) {
            this.fileList = [{
              name: this.form.fileName || '附件',
              url: this.form.fileUrl
            }]
          }
        });
      }
    },
    // 处理文件选择（当用户选择文件或文件状态变化时触发）
    handleFileChange(file, fileList) {
      // 限制只保留一个文件（配合limit=1）
      if (fileList.length > 1) {
        // 移除第一个文件，只保留最新选择的
        fileList.shift();
      }
      // 更新文件列表（关键：将处理后的fileList赋值给this.fileList）
      this.fileList = fileList;
    },

    // 移除文件
    handleFileRemove(file, fileList) {
      // 直接使用el-upload返回的处理后的fileList（已过滤删除的文件）
      this.fileList = fileList;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传1个文件`);
    },
    // 修改submitForm方法
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = new FormData();
          const raData = { ...this.form };
          formData.append('reimbursementApplication', new Blob([JSON.stringify(raData)], {
            type: 'application/json'
          }));

          // 由于已经限制了只能有一个文件，直接取第一个即可
          if (this.fileList.length > 0) {
            const file = this.fileList[0].raw;
            console.log(file)
            if (file instanceof File) {
              formData.append('file', file);
            }
          }

          if (this.form.id != undefined) {
            // 修改操作（调用PUT接口）
            updateApplication(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.msgError("修改失败：" + (error.response?.data?.msg || error.message));
            });
          } else {
            // 新增操作（调用POST接口）
            addApplication(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.msgError("新增失败：" + (error.response?.data?.msg || error.message));
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      delApplication(row.id).then(response => {
        this.$modal.msgSuccess("删除成功")
        this.getList()
      })
    },
    handleUpdate(row) {
      if (row) {
        this.reset();
        getApplication(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          // 新增：设置为非添加模式
          this.isAddMode = false
          this.isSub=true;
          this.form.paymentMethod = this.form.paymentMethod?.toString();
          this.form.userName = response.data.user?.userName || '';
          this.title = "修改报销申请";
          this.isApprovalView = false;

          // 处理文件列表回显
          if (this.form.fileUrl) {
            this.fileList = [{
              name: this.form.fileName || '附件',
              url: this.form.fileUrl
            }]
          }
        });
      }
    },
    // 2. 处理项目选择变化（核心联动逻辑）
    handleProjectChange(val) {
      if (!val) {
        this.form.projectNo = "";
        return;
      }
      // 从项目列表中找到选中的项目
      const selectedProject = this.projectList.find(item => item.id === val);
      if (selectedProject) {
        // 自动填充项目编号
        this.form.projectNo = selectedProject.projectNo || "";
      } else {
        this.form.projectNo = "";
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/fm/ra/export', {
        ...this.queryParams
      }, `application_${new Date().getTime()}.xlsx`)
    }
  },
  // 3. 监听项目ID变化，确保联动生效
  watch: {
    'form.projectId'(val) {
      this.handleProjectChange(val);
    }
  }
}
</script>
